{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4Pjmz-RORV8E"
      },
      "source": [
        "# Apply labels with zero-shot classification\n",
        "\n",
        "This notebook shows how zero-shot classification can be used to perform text classification, labeling and topic modeling. txtai provides a light-weight wrapper around the zero-shot-classification pipeline in Hugging Face Transformers. This method works impressively well out of the box. Kudos to the Hugging Face team for the phenomenal work on zero-shot classification!\n",
        "\n",
        "The examples in this notebook pick the best matching label using a list of labels for a snippet of text.\n",
        "\n",
        "[tldrstory](https://github.com/neuml/tldrstory) has full-stack implementation of a zero-shot classification system using Streamlit, FastAPI and Hugging Face Transformers. There is also a [Medium article describing tldrstory](https://towardsdatascience.com/tldrstory-ai-powered-understanding-of-headlines-and-story-text-fc86abd702fc) and zero-shot classification. \n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Dk31rbYjSTYm"
      },
      "source": [
        "# Install dependencies\n",
        "\n",
        "Install `txtai` and all dependencies."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "XMQuuun2R06J"
      },
      "source": [
        "%%capture\n",
        "!pip install git+https://github.com/neuml/txtai"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PNPJ95cdTKSS"
      },
      "source": [
        "# Create a Labels instance\n",
        "\n",
        "The Labels instance is the main entrypoint for zero-shot classification. This is a light-weight wrapper around the zero-shot-classification pipeline in Hugging Face Transformers.\n",
        "\n",
        "In addition to the default model, additional models can be found on the [Hugging Face model hub](https://huggingface.co/models?search=mnli).\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "nTDwXOUeTH2-"
      },
      "source": [
        "%%capture\n",
        "\n",
        "from txtai.pipeline import Labels\n",
        "\n",
        "# Create labels model\n",
        "labels = Labels()\n",
        "\n",
        "# Alternate models can be used via passing the model path as shown below\n",
        "# labels = Labels(\"roberta-large-mnli\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-vGR_piwZZO6"
      },
      "source": [
        "# Applying labels to text\n",
        "\n",
        "The example below shows how a zero-shot classifier can be applied to arbitary text. The default model for the zero-shot classification pipeline is *bart-large-mnli*. \n",
        "\n",
        "Look at the results below. It's nothing short of amazing✨ how well it performs. These aren't all simple even for a human. For example, intercepted was purposely picked as that is more common in football than basketball. The amount of knowledge stored in larger Transformer models continues to impress me. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "-K2YJJzsVtfq",
        "outputId": "7a1edf58-15e0-46c8-958e-3a8e6045f802"
      },
      "source": [
        "data = [\"Dodgers lose again, give up 3 HRs in a loss to the Giants\",\n",
        "        \"Giants 5 Cardinals 4 final in extra innings\",\n",
        "        \"Dodgers drop Game 2 against the Giants, 5-4\",\n",
        "        \"Flyers 4 Lightning 1 final. 45 saves for the Lightning.\",\n",
        "        \"Slashing, penalty, 2 minute power play coming up\",\n",
        "        \"What a stick save!\",\n",
        "        \"Leads the NFL in sacks with 9.5\",\n",
        "        \"UCF 38 Temple 13\",\n",
        "        \"With the 30 yard completion, down to the 10 yard line\",\n",
        "        \"Drains the 3pt shot!!, 0:15 remaining in the game\",\n",
        "        \"Intercepted! Drives down the court and shoots for the win\",\n",
        "        \"Massive dunk!!! they are now up by 15 with 2 minutes to go\"]\n",
        "\n",
        "# List of labels\n",
        "tags = [\"Baseball\", \"Football\", \"Hockey\", \"Basketball\"]\n",
        "\n",
        "print(\"%-75s %s\" % (\"Text\", \"Label\"))\n",
        "print(\"-\" * 100)\n",
        "\n",
        "for text in data:\n",
        "    print(\"%-75s %s\" % (text, tags[labels(text, tags)[0][0]]))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Text                                                                        Label\n",
            "----------------------------------------------------------------------------------------------------\n",
            "Dodgers lose again, give up 3 HRs in a loss to the Giants                   Baseball\n",
            "Giants 5 Cardinals 4 final in extra innings                                 Baseball\n",
            "Dodgers drop Game 2 against the Giants, 5-4                                 Baseball\n",
            "Flyers 4 Lightning 1 final. 45 saves for the Lightning.                     Hockey\n",
            "Slashing, penalty, 2 minute power play coming up                            Hockey\n",
            "What a stick save!                                                          Hockey\n",
            "Leads the NFL in sacks with 9.5                                             Football\n",
            "UCF 38 Temple 13                                                            Football\n",
            "With the 30 yard completion, down to the 10 yard line                       Football\n",
            "Drains the 3pt shot!!, 0:15 remaining in the game                           Basketball\n",
            "Intercepted! Drives down the court and shoots for the win                   Basketball\n",
            "Massive dunk!!! they are now up by 15 with 2 minutes to go                  Basketball\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "t-tGAzCxsHLy"
      },
      "source": [
        "# Let's try emoji 😀\n",
        "\n",
        "Does the model have knowledge of emoji? Check out the run below, sure looks like it does! Notice the labels are applied based on the perspective from which the information is presented. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "uIf064M9pbjn",
        "outputId": "1d104014-e9ca-4c89-d259-2b5b231840ad"
      },
      "source": [
        "tags = [\"😀\", \"😡\"]\n",
        "\n",
        "print(\"%-75s %s\" % (\"Text\", \"Label\"))\n",
        "print(\"-\" * 100)\n",
        "\n",
        "for text in data:\n",
        "    print(\"%-75s %s\" % (text, tags[labels(text, tags)[0][0]]))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Text                                                                        Label\n",
            "----------------------------------------------------------------------------------------------------\n",
            "Dodgers lose again, give up 3 HRs in a loss to the Giants                   😡\n",
            "Giants 5 Cardinals 4 final in extra innings                                 😀\n",
            "Dodgers drop Game 2 against the Giants, 5-4                                 😡\n",
            "Flyers 4 Lightning 1 final. 45 saves for the Lightning.                     😀\n",
            "Slashing, penalty, 2 minute power play coming up                            😡\n",
            "What a stick save!                                                          😀\n",
            "Leads the NFL in sacks with 9.5                                             😀\n",
            "UCF 38 Temple 13                                                            😀\n",
            "With the 30 yard completion, down to the 10 yard line                       😀\n",
            "Drains the 3pt shot!!, 0:15 remaining in the game                           😀\n",
            "Intercepted! Drives down the court and shoots for the win                   😀\n",
            "Massive dunk!!! they are now up by 15 with 2 minutes to go                  😀\n"
          ]
        }
      ]
    }
  ]
}